package com.example.baseapp.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.example.baseapp.admin.entity.Menu;
import com.example.baseapp.admin.mapper.MenuMapper;
import com.example.baseapp.admin.service.MenuService;
import com.example.baseapp.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * 菜单表(Menu)表服务实现类
 *
 * @author zhanglei
 * @since 2022-04-28 14:24:38
 */
@Slf4j
@Service("menuService")
public class MenuServiceImpl implements MenuService {
    @Resource
    private MenuMapper menuMapper;

    @Override
    public void insert(Menu menu) {

        log.debug("创建菜单信息 -->:{}",menu);
        int i = menuMapper.insert(menu);
        if (i == 0) {
            throw BusinessException.createErrorException("创建失败");
        }
    }

    @Override
    public void update(Menu menu) {
        log.debug("更新菜单信息 -->:{}",menu);
        LambdaUpdateWrapper<Menu> lambdaUpdateWrapper = new LambdaUpdateWrapper<Menu>()
                .eq(Menu::getMenuId,menu.getMenuId());
        int i = menuMapper.update(menu,lambdaUpdateWrapper);
        if (i == 0) {
            throw BusinessException.createErrorException("更新失败");
        }
    }

    @Override
    public void delete(String menuId) {
        menuMapper.deleteById(new Menu().setMenuId(menuId));
    }

    @Override
    public Menu getMenuByMenuId(String menuId) {
        return menuMapper.selectOne(this.getLambdaQueryWrapper(new Menu()
                .setMenuId(menuId)
                .setStatus("S")));
    }

    @Override
    public List<Menu> getMenuByMenuId(List<String> menuIdList) {
        return menuMapper.selectList(new LambdaQueryWrapper<Menu>().in(Menu::getMenuId, menuIdList));
    }

    @Override
    public List<Menu> getMenuByMenuParentId(String menuParentId) {
        return menuMapper.selectList(this.getLambdaQueryWrapper(new Menu()
                .setMenuParentId(menuParentId)
                .setStatus("S")));
    }

    public LambdaQueryWrapper<Menu> getLambdaQueryWrapper(Menu menu) {
        return new LambdaQueryWrapper<Menu>()
                .eq(StringUtils.hasText(menu.getMenuId()), Menu::getMenuId, menu.getMenuId())
                .eq(StringUtils.hasText(menu.getMenuParentId()), Menu::getMenuParentId, menu.getMenuParentId())
                .eq(menu.getId() != null, Menu::getId, menu.getId())
                .eq(StringUtils.hasText(menu.getStatus()), Menu::getStatus, menu.getStatus());
    }
}